/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package serveur;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;


/**
 *
 * @author scriptoff
 */
public class TcpServeur {

    private int port ;
    private Chat chat;
    SSLServerSocket socket_ecoute ;


    String patternString = "AES.*";
    Pattern pattern = Pattern.compile(patternString);
    Matcher matcher;
    boolean matchFound;


    public TcpServeur(int port, Chat chat)  {
      this.chat = chat;
      this.port = port;
      try {
        SSLServerSocketFactory sf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
        socket_ecoute =   (SSLServerSocket)sf.createServerSocket(port);
        boucleAttenteClient();
      } catch (Exception ex) {
        new TraiteException(ex,"TcpServeur");
      }

    }

    public  void boucleAttenteClient()  {
        try {
            attenteClient();
        } catch (Exception ex) {
            new TraiteException(ex , "boucleAttenteClient");
        }
    }

    private void attenteClient()  {
        while(true) {
            try {
                SSLSocket socket_transfert = (SSLSocket) socket_ecoute.accept();
                String str[]=socket_transfert.getSupportedCipherSuites();


                int tailleTableau = str.length;
                int tailleAes = 0 ;
                for (int i=0; i < tailleTableau; i++) {


                    matcher = pattern.matcher(str[i]);
                    matchFound = matcher.find();
                    if ( matchFound )
                        tailleAes++;
                }


                
                String set[] = new String[tailleAes];

                int j = 0;
                for (int i=0; i < tailleTableau; i++) {

        
                matcher = pattern.matcher(str[i]);
                matchFound = matcher.find();

                if (matchFound)
                    set[j++] = str[i];
                }
                socket_transfert.setEnabledCipherSuites(set);
                System.out.println(socket_transfert.getSession().getCipherSuite());
                TraitementClient tc = new TraitementClient(socket_transfert, chat);
                Thread th = new Thread (tc);
                th.start();
            } catch (Exception ex) {
                new TraiteException(ex,"attenteClient");
            }
        }
    }
  
}
